// 0. 创建一个文件夹 router/router.js
// 1. 引入 路由
import Vue from 'vue'
import VueRouter from 'vue-router'

/**
 * 具体步骤（home login）
 *1.把需要的组件以单文件的形式创建出

 *2.按照以下四步骤

 *入口-手动
 *匹配规则
 *组件-引入
 *出口-App.vue 跟组件里面
 */

// 引入子组件

import Login from '../components/login/Login.vue'
import Home from '../components/home/Home.vue'
import Users from '../components/users/Users.vue'
import Roles from '../components/roles/Roles.vue'
import Rights from '../components/rights/Rights.vue'

// 2. 把 路由当成插件安装
Vue.use(VueRouter)
// 3. 实例化路由，将路由挂载到vue实例上
const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      children: [
        { path: '/users', component: Users },
        { path: '/roles', component: Roles },
        { path: '/rights', component: Rights }
      ]
    }
  ]
})
// 導航守衛：攔截
// 參數一 to :即將要跳轉的路由對象
// 參數二：from 從哪來
//  參數三：next()下一步

router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    let token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})
// 4. 导出路由
export default router
